﻿using System;
using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Tables
{
    /// <summary>
    /// Reads the contents of a SQL table row into a given object type.
    /// </summary>
    public static class CreateCommand
    {
        private const string Sql = @"CREATE TABLE `{0}` ({1});";

        /// <summary>
        /// Creates the table for the given type.
        /// </summary>
        /// <returns></returns>
        public static void Execute(Type type, Connection connection)
        {
            // Check table doesn't exist
            if (ExistsCommand.Execute(type, connection))
            {
                throw new ApplicationException("Table already exists for " + type.Name);
            }

            // Execute connection & command
            using (var dbConnection = connection.Open())
            {
                using (var command = dbConnection.CreateCommand())
                {
                    // Get SQL ingredients
                    var tableName = TableNameFinder.Find(type);
                    var columns = ColumnFinder.Find(type);

                    // build SQL statement
                    command.CommandText = string.Format(Sql, tableName, columns.ToCreateTableSql());

                    // Execute!
                    command.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// Creates the table for the given type.
        /// </summary>
        /// <returns></returns>
        public static void Execute<T>(Connection connection)
        {
            Execute(typeof(T), connection);
        }
    }
}